<!-- 店铺列表页面 -->
<template>
	<view class="shop-list">
		<!-- 自定义导航栏 -->
		<!-- <cu-custom bgColor="bg-white" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">选择门店</block>
		</cu-custom> -->
		<view class="container">
			<!-- 搜索区域 -->
			<view class="search-section">
				<view class="location-selector" @click="goSelectCity">
					<text class="cuIcon-location text-gray"></text>
					<text class="location-text">{{ city || '全部' }}</text>
				</view>
				<view class="search-input">
					<view class="cu-bar search">
						<view class="search-form round">
							<text class="cuIcon-search"></text>
							<input type="text" placeholder="搜索门店" v-model="searchText" @blur="searchShop" />
						</view>
					</view>
				</view>
			</view>

			<!-- 商家列表 -->
			<scroll-view class="scroll-area" scroll-y="true" @scrolltolower="loadMore" :refresher-enabled="false"
				:refresher-triggered="refreshing">
				<view class="store-list">
					<view class="store-item" v-for="(store, index) in shopList" :key="index" @click="goReserve(store)">
						<!-- 商家图片 -->
						<view class="store-image">
							<image :src="globalConfig.site_url + store.image" mode="aspectFill" class="image"></image>
							<view class="brand-name">{{ store.title }}</view>
							<view class="slogan">{{ store.slogan }}</view>
						</view>

						<!-- 商家信息 -->
						<view class="store-info">
							<!-- 标签 -->
							<view class="tags">
								<text class="tag" v-for="(tag, tagIndex) in store.type_list" :key="tagIndex">
									{{ tag }}
								</text>
							</view>

							<!-- 商家名称 -->
							<text class="store-name">{{ store.name }}</text>

							<!-- 距离信息 -->
							<view class="distance-info">
								<text class="distance">距离 {{ store.distance }}{{ store.address }}</text>
							</view>

							<!-- 营业时间 -->
							<view class="business-hours">
								<text class="hours">营业时间：{{ store.shop_time }}</text>
							</view>

							<!-- 特殊标签 -->
							<view class="special-tag" v-if="store.specialTag">
								<text class="special-text">{{ store.specialTag }}</text>
							</view>

							<!-- 操作按钮 -->
							<view class="action-buttons">
								<view class="action-btn" @click.stop="navigate(store)">
									<text class="btn-text">导航</text>
								</view>
								<view class="action-btn" @click.stop="makeCall(store)">
									<text class="btn-text">电话</text>
								</view>
								<view class="action-btn primary" @click.stop="selectShop(store.id, store.title)">
					<text class="btn-text primary-text">选择TA</text>
				</view>
							</view>
						</view>

						<!-- 营业状态 -->
						<view class="business-status" v-if="store.isOpen">
							<view class="status-dot"></view>
							<text class="status-text">营业中</text>
						</view>
					</view>
				</view>

				<!-- 加载更多提示 -->
				<view class="loading-more" v-if="loading">
					<text class="loading-text">加载中...</text>
				</view>

				<view class="no-more" v-if="noMore">
					<text class="no-more-text">没有更多数据了</text>
				</view>
			</scroll-view>

		</view>

		<!-- uView登录弹窗 (from shop-list.vue) -->
		<u-popup v-model="showLoginPopup" mode="center" border-radius="16" width="600rpx" :mask-close-able="true"
			@close="closeLoginPopup">
			<view class="login-popup">
				<view class="popup-header">
					<view class="popup-title">登录</view>
					<view class="popup-close" @click="closeLoginPopup">
						<u-icon name="close" color="#999" size="20"></u-icon>
					</view>
				</view>

				<view class="login-methods">
					<u-button type="success" shape="round" :loading="wechatLoading" @click="handleWechatLogin"
						:custom-style="{ backgroundColor: '#07c160', borderColor: '#07c160', marginBottom: '20rpx' }">
						<u-icon name="weixin-fill" color="#fff" size="20" style="margin-right: 10rpx"></u-icon>
						{{ wechatLoading ? '登录中...' : '微信登录' }}
					</u-button>
				</view>

				<view class="login-tips">
					<u-checkbox v-model="agreePolicy" shape="circle" active-color="#007aff" :size="32" style="margin-right: 10rpx;" />
					<text class="tips-text">我已阅读并同意</text>
					<text class="link-text" @click="showPrivacy('agreement')">《用户协议》</text>
					<text class="tips-text">和</text>
					<text class="link-text" @click="showPrivacy('policy')">《隐私政策》</text>
				</view>
			</view>
		</u-popup>

	</view>
</template>

<script>
import request from '@/common/request.js';
import { mapGetters, mapActions, mapState } from 'vuex';
import { checkLoginStatus, wechatMiniLogin } from '@/common/auth.js';
export default {
	data() {
		return {
			showLoginPopup: false,
			wechatLoading: false,
			selectedStore: null,
			config: {},
			city: '',
			searchText: '',
			activeTab: 0,
			categories: [],
			shopList: [],
			type_list: [],
			loading: false,
			refreshing: false,
			noMore: false,
			page: 1,
			pageSize: 10,
			type_id: '',
			latitude: 0,
			longitude: 0
		};
	},
	computed: {
		// 使用mapGetters获取全局状态
		...mapGetters([
			'getGaodeKey',
			'getSiteName',
			'getLocation'
		]),

		// 使用mapState直接访问state
		...mapState({
			globalConfig: state => state.config,
			userLocation: state => state.location,
		})
	},
	// 获取页面地址参数
	onLoad(options) {
		console.log(options, 'onLoad');
		this.type_id = options.type || '1';
		uni.$on('citySelected', (city) => {
			this.city = city;
			console.log('选择的城市是：', city);
			this.getShopList();
		});
	},
	mounted() {
		this.getTypeList();
		this.getShopList();
	},
	methods: {
	selectShop(shopId, shopName) {
		const pages = getCurrentPages();
		const prevPage = pages[pages.length - 2];
		// 直接修改上一页的表单数据
		// 设置选中的店铺数据到上一页
		// 直接设置上一页的selectedShop属性
		// 使用$set设置上一页数据确保响应式
		// 直接赋值已声明的响应式属性
		// 使用事件总线传递店铺选择结果
		// 发送事件并在nextTick后返回确保事件被接收
		// 将选中的店铺数据存储到Vuex
		this.$store.commit('setSelectedShop', {
			id: shopId,
			name: shopName
		});
		uni.navigateBack({ delta: 1 });
	},
		searchShop() {
			this.getShopList();
		},
		// 获取位置信息
		getAddressData() {
			uni.getLocation({
				type: 'gcj02', // 返回GPS坐标（或 'gcj02' 国测局坐标）
				success: (res) => {
					console.log(res, '获取位置信息');
					const { latitude, longitude } = res;
					console.log('当前位置:', latitude, longitude);
					this.latitude = latitude;
					this.longitude = longitude;
					// 可选：逆地理编码获取城市名
					this.reverseGeocode(latitude, longitude, this.config.gaode_key);
				},
				fail: (err) => {
					console.error('定位失败:', err);
				}

			});
		},
		// 逆地理编码函数
		reverseGeocode(lat, lng, key) {
			console.log(lat, lng, key);
			uni.request({
				url: 'https://restapi.amap.com/v3/geocode/regeo',
				data: {
					key: key,
					location: `${lng},${lat}`
				},
				success: (res) => {
					console.log(res, '逆地理编码');
					if (res.data.statusCode == '1') {
						const city = res.data.regeocode.addressComponent.district;
						if (city) {
							this.city = city;
						}
						console.log('当前城市:', city);
					}
				}
			});
		},
		// 选择位置
		goSelectCity() {
			uni.navigateTo({
				url: '/pages/shop/select-city'
			})
		},
		// 切换分类
		switchTab(item) {
			this.type_id = item.id
			this.page = 1
			this.getShopList()
		},
		// 请求分类数据
		getTypeList() {
			let opts = {
				url: '/api/index/getTypeList',
				method: 'post'
			};
			uni.showLoading({
				title: '加载中'
			});
			request.httpRequest(opts).then(res => {
				uni.hideLoading();
				console.log(res.data.data, 'getTypeList');
				this.type_list = res.data.data || []
			});
		},
		// 获取店铺列表
		getShopList() {
			let opts = {
				url: '/api/index/getShopList?page=' + this.page + '&type_id=' + this.type_id + '&city=' + this.city + '&latitude=' + this.latitude + '&longitude=' + this.longitude + '&title=' + this.searchText,
				method: 'get',
			};
			uni.showLoading({
				title: '加载中'
			});
			request.httpRequest(opts).then(res => {
				uni.hideLoading();
				console.log(res, 'getShopList');
				const resData = res.data.data
				this.shopList = resData.list
				this.page = resData.current_page
				this.totalPage = resData.total
				this.refreshing = false
				if (this.page >= this.totalPage) {
					this.noMore = true
				}
			});
		},
		// 下拉刷新
		async onRefresh() {
			this.refreshing = true
			this.page = 1
			this.noMore = false

			try {
				await this.getShopList()
				uni.showToast({
					title: '刷新成功',
					icon: 'success'
				})
			} catch (error) {
				uni.showToast({
					title: '刷新失败',
					icon: 'none'
				})
			}
		},

		// 加载更多
		async loadMore() {
			if (this.loading || this.noMore) return

			this.loading = true
			this.page++

			try {
				await this.getShopList()
			} catch (error) {
				this.page-- // 失败时回退页码
			}
		},

		// 导航
		navigate(store) {
			console.log(store);
			uni.openLocation({
				latitude: parseFloat(store.lat),
				longitude: parseFloat(store.lng),
				name: store.title || '店铺',
				address: store.address || ''
			})
		},

		// 拨打电话
		makeCall(store) {
			if (!store.mobile) {
				uni.showToast({
					title: '店铺电话不存在',
					icon: 'none'
				})
				return
			}

			uni.makePhoneCall({
				phoneNumber: store.mobile
			})
		},

		// 去预定
		async goReserve(store) {
			const isLoggedIn = await checkLoginStatus();
			if (isLoggedIn) {
				uni.navigateTo({
					url: '/pages/shop/shop-detail?id=' + store.id
				})
			} else {
				this.selectedStore = store;
				this.showLoginPopup = true;
			}
		},

		// 去充值
		goRecharge() {
			uni.navigateTo({
				url: '/pages/user/recharge'
			})
		},

		// --- Login Logic from me.vue ---
		closeLoginPopup() {
			this.showLoginPopup = false;
			this.wechatLoading = false;
		},

		async handleWechatLogin() {
			if (this.wechatLoading) return;
			if (!this.agreePolicy) {
				this.$u.toast('请先勾选同意《用户协议》和《隐私政策》');
				return;
			}
			this.wechatLoading = true;
			try {
				const result = await wechatMiniLogin();
				if (result.success) {
					this.$store.dispatch('fetchUserInfoAction'); // 更新全局用户信息
					this.closeLoginPopup();
					this.$u.toast('登录成功');

					// 登录成功后，跳转到之前选中的店铺
					if (this.selectedStore) {
						uni.navigateTo({
							url: '/pages/shop/shop-detail?id=' + this.selectedStore.id
						});
						this.selectedStore = null; // 清除暂存
					}
				} else {
					throw new Error(result.message || '登录失败');
				}
			} catch (error) {
				this.$u.toast(error.message || '登录操作失败');
			} finally {
				this.wechatLoading = false;
			}
		},

		showPrivacy(type) {
			const urlKey = type === 'policy' ? 'yszc_url' : 'yhxy_url';
			const title = type === 'policy' ? '隐私政策' : '用户协议';
			if (this.globalConfig && this.globalConfig[urlKey]) {
				uni.navigateTo({
					url: `/pages/common/webview?url=${encodeURIComponent(this.globalConfig[urlKey])}&title=${encodeURIComponent(title)}`
				});
			} else {
				this.$u.toast('协议地址未配置');
			}
		},
	},
}
</script>

<style lang="scss" scoped>
.container {
	background-color: #f8f8f8;
}

.search-section {
	display: flex;
	align-items: center;
	padding: 20rpx 30rpx;
	background: white;

	.location-selector {
		display: flex;
		align-items: center;
		margin-right: 20rpx;

		.cuIcon-location {
			margin-right: 10rpx;
			font-size: 32rpx;
		}

		.location-text {
			font-size: 28rpx;
			color: #666;
		}
	}

	.search-input {
		flex: 1;
	}
}

.category-tabs {
	background: white;
	margin-bottom: 20rpx;
	padding: 20rpx 30rpx;

	.nav {
		white-space: nowrap;

		.category-item {
			border-radius: 50rpx;
			margin: 10rpx;
			font-size: 28rpx;
		}

		.active {
			color: #333;
		}
	}
}

/* 滚动区域 */
.scroll-area {
	flex: 1;
	padding: 0 20rpx;
	padding-bottom: 150rpx;
}

/* 商家列表 */
.store-list {
	padding: 20rpx 0;
}

.store-item {
	background-color: #fff;
	border-radius: 20rpx;
	margin-bottom: 20rpx;
	padding: 30rpx;
	display: flex;
	position: relative;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

/* 商家图片 */
.store-image {
	width: 200rpx;
	height: 280rpx;
	border-radius: 15rpx;
	overflow: hidden;
	position: relative;
	margin-right: 30rpx;
}

.image {
	width: 100%;
	height: 100%;
}

.brand-name {
	position: absolute;
	top: 20rpx;
	left: 20rpx;
	right: 20rpx;
	color: #fff;
	font-size: 24rpx;
	text-align: center;
	background-color: rgba(0, 0, 0, 0.5);
	border-radius: 10rpx;
	padding: 10rpx;
}

.slogan {
	position: absolute;
	bottom: 20rpx;
	left: 20rpx;
	right: 20rpx;
	color: #fff;
	font-size: 22rpx;
	text-align: center;
	background-color: rgba(0, 0, 0, 0.5);
	border-radius: 10rpx;
	padding: 8rpx;
}

/* 商家信息 */
.store-info {
	flex: 1;
	display: flex;
	flex-direction: column;
}

/* 标签 */
.tags {
	display: flex;
	flex-wrap: wrap;
	margin-bottom: 20rpx;
}

.tag {
	background-color: #007AFF;
	color: #fff;
	font-size: 22rpx;
	padding: 8rpx 16rpx;
	border-radius: 8rpx;
	margin-right: 10rpx;
	margin-bottom: 10rpx;
}

/* 商家名称 */
.store-name {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 15rpx;
	line-height: 1.4;
}

/* 距离信息 */
.distance-info {
	display: flex;
	align-items: center;
	margin-bottom: 10rpx;
}

.distance {
	color: #666;
	font-size: 26rpx;
}

/* 营业时间 */
.business-hours {
	margin-bottom: 15rpx;
}

.hours {
	color: #666;
	font-size: 26rpx;
}

/* 特殊标签 */
.special-tag {
	margin-bottom: 20rpx;
}

.special-text {
	background-color: #FFE4E1;
	color: #FF6B6B;
	font-size: 22rpx;
	padding: 8rpx 16rpx;
	border-radius: 8rpx;
}

/* 操作按钮 */
.action-buttons {
	display: flex;
	gap: 20rpx;
	margin-top: auto;
}

.action-btn {
	flex: 1;
	background-color: #f8f8f8;
	border-radius: 12rpx;
	padding: 20rpx;
	text-align: center;
}

.action-btn.primary {
	background-color: #007AFF;
}

.btn-text {
	font-size: 26rpx;
	color: #333;
}

.primary-text {
	color: #fff;
}

/* 营业状态 */
.business-status {
	position: absolute;
	top: 30rpx;
	right: 30rpx;
	display: flex;
	align-items: center;
}

.status-dot {
	width: 12rpx;
	height: 12rpx;
	background-color: #00C851;
	border-radius: 50%;
	margin-right: 8rpx;
}

.status-text {
	color: #00C851;
	font-size: 22rpx;
}

/* 加载状态 */
.loading-more,
.no-more {
	text-align: center;
	padding: 40rpx;
}

.loading-text,
.no-more-text {
	color: #999;
	font-size: 26rpx;
}

/* 底部导航 */
.bottom-nav {
	background-color: #fff;
	display: flex;
	border-top: 1rpx solid #eee;
	padding: 20rpx 0;
}

.nav-item {
	flex: 1;
	text-align: center;
	padding: 20rpx 0;
}

.nav-text {
	font-size: 24rpx;
	color: #999;
}

.nav-text.active {
	color: #007AFF;
}
</style>
